import type { Ref } from 'vue';

import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';

import type { VbenFormSchema } from '#/adapter/form';
import type { SystemPermissionApi } from '#/api/system/permission';
import type { VbenFormSchema } from '#/types/vben';

import { computed, h } from 'vue';

import {
  CommonStatusEnum,
  DICT_TYPE,
  SystemDataScopeEnum,
} from '@vben/constants';
import { getDictOptions } from '@vben/hooks';

import { Checkbox, Space } from 'ant-design-vue';

import { z } from '#/adapter/form';
import { getRangePickerDefaultProps } from '#/utils';
/** 新增/修改的表单 */
export function roleFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'name',
      label: '角色名称',
      component: 'Input',
      rules: 'required',
    },
    {
      fieldName: 'code',
      label: '角色标识',
      component: 'Input',
      rules: 'required',
    },
    {
      fieldName: 'sort',
      label: '显示顺序',
      component: 'InputNumber',
      componentProps: {
        min: 0,
        placeholder: '请输入显示顺序',
      },
      rules: 'required',
    },
    {
      fieldName: 'status',
      label: '角色状态',
      component: 'RadioGroup',
      componentProps: {
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
        buttonStyle: 'solid',
        optionType: 'button',
      },
      rules: z.number().default(CommonStatusEnum.ENABLE),
    },
    {
      fieldName: 'remark',
      label: '角色备注',
      component: 'Textarea',
    },
  ];
}

/** 分配数据权限的表单 */
export function useAssignDataPermissionFormSchema(
  editable: (() => boolean) | Ref<boolean>, // 响应式 editable
  userDataScope: Ref<number | undefined>,
): VbenFormSchema[] {
  const isDisabled = computed(() =>
    typeof editable === 'function' ? !editable() : !editable.value,
  );

  return [
    {
      component: 'Input',
      fieldName: 'id',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'name',
      label: '角色名称',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'code',
      label: '角色标识',
      componentProps: {
        disabled: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'dataScope',
      label: '权限范围',
      componentProps: () => {
        const allOptions = getDictOptions(
          DICT_TYPE.SYSTEM_DATA_SCOPE,
          'number',
        );
        if (userDataScope.value === null) {
          return { options: [], disabled: isDisabled.value };
        }
        return {
          options: allOptions.filter(
            (item) => Number(item.sort) >= Number(userDataScope.value),
          ),
          disabled: isDisabled.value,
        };
      },
    },
    {
      fieldName: 'dataScopeDeptIds',
      label: '部门范围',
      component: 'Input',
      formItemClass: 'items-start',
      dependencies: {
        triggerFields: ['dataScope'],
        show: (values) => {
          return values.dataScope === SystemDataScopeEnum.DEPT_CUSTOM;
        },
      },
    },
  ];
}

/** 分配菜单列表的字段 */
export function useAssignMenuFormGridColumns(
  checkedMenuIds: Ref<number[]>,
  onButtonCheckboxChange: (
    row: any,
    buttons: any[],
    btnId: number,
    checked: boolean,
  ) => void,
  editable: (() => boolean) | Ref<boolean>, // 响应式 editable
) {
  const isEditable =
    typeof editable === 'function' ? editable : () => editable.value;
  return [
    {
      type: 'checkbox',
      fixed: 'left',
      align: 'left',
      width: 40,
    },
    {
      field: 'name',
      title: '菜单',
      align: 'left',
      fixed: 'left',
      treeNode: true,
      width: 200,
    },
    {
      field: 'buttonMenus',
      title: '权限',
      align: 'left',
      showOverflow: false,
      slots: {
        default: ({ row }: any) => {
          const buttons = row.buttonMenus || [];
          return h(Space, { wrap: true }, () =>
            buttons.map((btn: any) =>
              h(
                Checkbox,
                {
                  checked: checkedMenuIds.value.includes(btn.id),
                  disabled: !isEditable(), // 行内按钮复选框禁用
                  onChange: (e: any) =>
                    onButtonCheckboxChange(
                      row,
                      buttons,
                      btn.id,
                      e.target.checked,
                    ),
                },
                { default: () => btn.name },
              ),
            ),
          );
        },
      },
    },
  ];
}
export function useAssignOperateFormGridColumns(
  checkedList: Ref<SystemPermissionApi.RoleOperateVO[]>,
  onNodeCheckboxChange: (
    row: any,
    nodes: SystemPermissionApi.RoleOperateVO[],
    node: SystemPermissionApi.RoleOperateVO,
    checked: boolean,
  ) => void,
  editable: (() => boolean) | Ref<boolean>, // 响应式 editable
) {
  const isEditable =
    typeof editable === 'function' ? editable : () => editable.value;
  return [
    {
      type: 'checkbox',
      fixed: 'left',
      align: 'left',
      width: 40,
    },
    {
      field: 'name',
      title: '业务名称',
      align: 'left',
      fixed: 'left',
      treeNode: true,
      width: 200,
    },
    {
      field: 'reviewList',
      title: '流程节点',
      align: 'left',
      showOverflow: false,
      slots: {
        default: ({ row }: any) => {
          const nodes = row.reviewList || [];
          return h(Space, { wrap: true }, () =>
            nodes.map((node: SystemPermissionApi.RoleOperateVO) =>
              h(
                Checkbox,
                {
                  checked: checkedList.value.some(
                    (item) =>
                      item.nodeCode === node.nodeCode && item.type === 2,
                  ),
                  disabled: !isEditable(), // 行内按钮复选框禁用
                  onChange: (e: any) =>
                    onNodeCheckboxChange(row, nodes, node, e.target.checked),
                },
                {
                  default: () =>
                    `第${node.num}级${node.alias ? node.alias : node.typeName}审核`,
                },
              ),
            ),
          );
        },
      },
    },
  ];
}
/** 用户列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'username',
      label: '用户名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入用户名称',
        allowClear: true,
      },
    },
    {
      fieldName: 'mobile',
      label: '手机号码',
      component: 'Input',
      componentProps: {
        placeholder: '请输入手机号码',
        allowClear: true,
      },
    },
    {
      fieldName: 'createTime',
      label: '创建时间',
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
  ];
}

/** 用户列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
  return [
    {
      field: 'id',
      title: '用户编号',
      visible: false,
    },
    {
      field: 'username',
      title: '用户名称',
    },
    {
      field: 'nickname',
      title: '用户昵称',
    },
    {
      field: 'fullName',
      title: '姓名',
    },
    {
      field: 'mobile',
      title: '手机号码',
    },
    {
      field: 'unitName',
      title: '单位',
    },
    {
      field: 'deptName',
      title: '部门',
    },

    {
      title: '操作',
      width: 180,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}
export function useGridAddColumns(): VxeTableGridOptions['columns'] {
  return [
    { type: 'checkbox', width: 40 },
    {
      field: 'id',
      title: '用户编号',
      visible: false,
    },
    {
      field: 'username',
      title: '用户名称',
    },
    {
      field: 'nickname',
      title: '用户昵称',
    },
    {
      field: 'fullName',
      title: '姓名',
    },
    {
      field: 'mobile',
      title: '手机号码',
    },
    {
      field: 'unitName',
      title: '单位',
    },
    {
      field: 'deptName',
      title: '部门',
    },
  ];
}
